﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SurvivalStrategy.Modules;
using SurvivalStrategy.Modules.Memory;
using SurvivalStrategy.Entities.EnitityComponents;

namespace SurvivalStrategy
{
    //klasa abstrakcyjna po ktorej dziedzicza wszystkie jednostki
    public class Entity //pozniej abstract
    {
        private int id;
        public int ID { get { return id; } }
        private EntityController controller;
        private RequestCommunicator requestCommunicator;
        private ActionManager actionManager;
        private EnitityInfo worldInfo;
        public EnitityInfo WorldInfo { get { return worldInfo; } }
        private Dictionary<string, MemorySegment> memory;
        public Dictionary<string, MemorySegment> Memory { get { return memory; } }
        private List<EntitiyComponent> components;

        public Entity(int id)
        {
            this.id = id;
            requestCommunicator = new RequestCommunicator(this);
            memory = new Dictionary<string, MemorySegment>();
            worldInfo = new EnitityInfo();
            components = new List<EntitiyComponent>();
        }

        public void Initialize()
        {
            actionManager = new ActionManager(id);
        }

        public void SetController(EntityController controller)
        {
            this.controller = controller;
            this.controller.SetRequestCommunicator(requestCommunicator);
            this.controller.SetID(id);
        }

        public virtual void Update()
        {
            controller.Update();
            actionManager.Update();
        }

        public void AddRequest(Request request)
        {
            actionManager.AddRequest(request);
        }

        public void AddBehaviorModule(BehaviorModule behaviorModule)
        {
            this.controller.AddModule(behaviorModule);
        }

        public void RemoveBehaviorModule(BehaviorModule behaviorModule)
        {
            this.controller.RemoveModule(behaviorModule);
        }

        public void AddActionModule(ActionModule actionModule)
        {
            this.actionManager.AddModule(actionModule);
        }

        public void RemoveActionModule(ActionModule actionModule)
        {
            this.actionManager.RemoveModule(actionModule);
        }

        public void AddComponent<T>() where T : EntitiyComponent, new()
        {
            if (this.GetComponent<T>() != null)
                return;
            T t = new T();
            t.SetOwner(this);
            components.Add(t);
        }

        public T GetComponent<T>() where T : EntitiyComponent
        {
            return (T)components.Find(c => (c.GetType() == typeof(T)));
        }
    }
}
